﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace XingFuStudio.Pioneer.Net {
    /// <summary>
    /// Cookie管理类
    /// </summary>
    public class CookieManager {

        /// <summary>
        /// 存放Cookie的文件夹
        /// </summary>
        private string cookieFolder = String.Empty;

        /// <summary>
        /// 序列化Cookie
        /// </summary>
        /// <param name="cookie">Cookie对象</param>
        /// <param name="key">序列化关键字，同时作为持久化Cookie的文件名称</param>
        public void SerializeCookie(CookieContainer cookie, string key) {
            try {
                string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cookieFolder), key + ".cookie");

                FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, cookie);
                fs.Close();

            } catch (Exception ex) {
                //throw ex;
            }
        }

        /// <summary>
        /// 反序列化Cookie
        /// </summary>
        /// <param name="key">序列化关键字，同时作为持久化Cookie的文件名称</param>
        public CookieContainer DeserialzeCookie(string key) {
            //初始化Cookie对象
            CookieContainer cookies = new CookieContainer();

            try {
                string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cookieFolder), key + ".cookie");

                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter bf = new BinaryFormatter();
                cookies = (CookieContainer)bf.Deserialize(fs);
                fs.Close();
            } catch (Exception ex) {
                //throw ex;
            }

            //返回Cookie
            return cookies;
        }

        /// <summary>
        /// 获取或设置存放Cookie的文件夹，为空时存在与主程序同一文件夹下
        /// </summary>
        public string CookieFolder {
            get {
                return cookieFolder;
            }
            set {
                cookieFolder = value;

                //判断是否设置了数据文件夹
                if (!String.IsNullOrEmpty(cookieFolder)) {
                    //判断设置的数据文件夹是否存在
                    if (!Directory.Exists(cookieFolder)) {
                        //不存在,创建数据文件夹
                        Directory.CreateDirectory(cookieFolder);
                    }
                }
            }
        }
    }
}
